In programming languages, we call the value of the data stored “Variable”. There are mainly the following types:
The way to declare a variable in a program:
type variableName = value;
/* Example:
int number = 1206;
char grade = 'A';
String name = "Chi"; */
The usage modes and restrictions of each variable will be introduced one by one below!!!
(Markdown is included in a class, and only part of the code is displayed for instructional purposes.)
byte (1 byte)
Number range: -128 to 127
short (2 bytes)
Number range: -32768 to 32767
int (4 bytes)
Number range: 2147483648 to 2147483647
long (8 bytes)
Number range: 9223372036854775808 ~ 9223372036854775807 (declared value must be followed by the L identifier)
byte number1 = 126;
short number2 = 12060;
int number3 = 120600;
long number4 = 12060000000L
float (4 bytes)
Range of decimal places stored: approximately 6 to 7 decimal places
double (8 bytes)
Range of decimal places stored: approximately 15 decimal places
The respective identifier, f or d, must be added after the declared value.
float flnum = 12.6f;
double dounum = 12.666d;
Occupied 2 bytes (bits) and can be used to store not only a single character, but also the values in the ASCII table.
char grade = 'S';
char first = 67, second = 72, third = 73; /*也可以一次宣告多個字串*/
System.out.println(grade); /* Outputs : S */
System.out.print(first);
System.out.print(second);
System.out.print(third); /* Outputs : CHI */
String is considered a relatively special Non-Primitive Data Type, and this section will introduce it in detail on Day 6.
Declare the use of the keyword String, and enclose the content in double quotation marks “”.
String name = "Chi";
String greeting = "Hello";
System.out.println(name + " " + greeting); /* Outputs : Chi Hello */
/*可以用 + 號把字串給串起來並印出*/
Boolean type variables are declared using the keyword boolean, and their contents can only be accessed as true or false (lowercase)
boolean myNameIsChi = true;
boolean isYourNameYu = false;
System.out.println(myNameIsChi); //Outputs : true
System.out.println(isYourNameYu); //Outputs : false
int num = 0;
boolean infinity = true;
while(infinity){ /*infinity內容為true,所以迴圈會一直執行進入*/
if(num == 10){ /*直到num = 10時才停止跳出*/
break;
}
num++;
}